package com.mb.common.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.Date;

/**
 * oss存储
 *
 * @author
 * @create 2018-07-09 下午1:53
 **/
@Slf4j
public class OSSUtil {

    // Endpoint以杭州为例，其它Region请按实际情况填写
    private static final String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
    private static final String accessKeyId = "LTAIc1lN0lhoyQHY";
    private static final String accessKeySecret = "aJLaJC6E73pG8iw6fWl243OuspqYOR";
    private static final String bucketName = "u20129-img";
    private static OSSClient ossClient;

//    static {
//        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
//    }

    /**
     * 上传文件
     * @param content
     * @return
     */
    public static String uploadImg(String key,byte[] content,String contentType){
        String filePath = "";
//        String bucketName = "u20129-img";

//        if(ossClient == null){
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
//        }

        //判断文件夹是否存在并创建
        checkAndCreateFolder(bucketName, key,true);

        ObjectMetadata objectMetadata = new ObjectMetadata();
        if(StringUtils.isBlank(contentType)){
            contentType = "image/png";
        }
        objectMetadata.setContentType(contentType);

        // 上传Byte数组
        ossClient.putObject(bucketName, key, new ByteArrayInputStream(content),objectMetadata);
        filePath = getUrl(bucketName,key);
        ossClient.shutdown();
        return filePath;
    }


    //上传视频
    public static String uploadVideoOSS(String key, byte[] content,String fileName) {
        String filePath = "";
//        String bucketName = "u20129-img";

//        if(ossClient == null){
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
//        }
        //判断文件夹是否存在并创建
        checkAndCreateFolder(bucketName, key,true);

        log.info("上传到路径" + key);
        Long fileSize = (long) content.length;
        // 创建上传Object的Metadata
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(fileSize);
        // 指定该Object被下载时的网页的缓存行为
        metadata.setCacheControl("no-cache");
        // 指定该Object下设置Header
        metadata.setHeader("Pragma", "no-cache");
        // 指定该Object被下载时的内容编码格式
        metadata.setContentEncoding("utf-8");
        // 文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
        // 如果没有扩展名则填默认值application/octet-stream
        metadata.setContentType(getContentType(fileName));
        // 指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
        metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");

        PutObjectResult putResult = ossClient.putObject(bucketName,key, new ByteArrayInputStream(content),
                metadata);
        ossClient.shutdown();
        filePath = getUrl(bucketName,key);
        ossClient.shutdown();
        return filePath;
    }


    /**
     * 判断文件夹是否存在
     * @param bucketName
     * @param key
     * @return
     */
    public static void checkAndCreateFolder(String bucketName, String key,boolean isAutoCreate){
        // 判断文件是否存在
        int index = key.lastIndexOf("/");
        String keySuffixWithSlash = key.substring(0,index);
        boolean isExist = ossClient.doesObjectExist(bucketName, keySuffixWithSlash);
        if(!isExist && isAutoCreate){
            createFolder(bucketName,keySuffixWithSlash);
        }
    }


    /**
     * 创建文件夹
     * @param bucketName
     * @param keySuffixWithSlash
     */
    public static void createFolder(String bucketName, String keySuffixWithSlash){
        ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
    }


    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public static String getUrl(String bucketName, String key) {
        // 设置URL过期时间为20年  3600l* 1000*24*365*20
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }


    /**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     *
     * @param fileName
     *            文件名
     * @return 文件的contentType
     */
    public static String getContentType(String fileName) {
        // 文件的后缀名
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if (".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)
                || ".png".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        }
        if (".html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        if (".mp4".equalsIgnoreCase(fileExtension)) {
            return "video/mp4";
        }
        // 默认返回类型
        return "image/jpeg";
    }



}
